package cc.rengu.igas.bsps.core.service.trans;


import cc.rengu.igas.acct.facade.bean.MchtAdjustDetail;
import cc.rengu.igas.acct.facade.request.VirtAcctMultiMchntAdjustRequest;
import cc.rengu.igas.bsps.common.constant.BspsAppParamConstant;
import cc.rengu.igas.bsps.common.constant.BspsTreeNodeConstant;
import cc.rengu.igas.bsps.common.enums.MchntTypeEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.BizStatusEnum;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.TxnInfoService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.service.realize.impl.TxnInfoServiceImpl;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.RedisUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author zhangxuran
 * @date 2020/5/13 21:12
 * @Description: 异步进行虚拟账户单笔记账
 */
public class AsynMchntVirtAcctMultiAdjustService extends RadpService {

    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        try {
            MchntOrderInfo mchntOrderInfo = (MchntOrderInfo) xmlTreeUtil.getXmlTreeObjectValue(BspsTreeNodeConstant.MCHNT_ORDER_INFO, MchntOrderInfo.class);
            PayOrderInfo payOrderInfo = (PayOrderInfo) xmlTreeUtil.getXmlTreeObjectValue(BspsTreeNodeConstant.PAY_ORDER_INFO, PayOrderInfo.class);
            UserOrderInfo userOrderInfo = (UserOrderInfo) xmlTreeUtil.getXmlTreeObjectValue(BspsTreeNodeConstant.USER_ORDER_INFO, UserOrderInfo.class);
            if (null == mchntOrderInfo || null == payOrderInfo || null == userOrderInfo) {
                rglog.error("商户订单或支付订单为空，异步进行虚拟账户记账失败");
                return -1;
            }
            String sysSeqNum = mchntOrderInfo.getSysSeqNum();

            MchntService mchntService = new MchntServiceImpl();
            MchntInfo mchntInfo = mchntService.getMchntInfo(mchntOrderInfo.getInstId(), mchntOrderInfo.getMchntNo());
            if (null == mchntInfo) {
                rglog.error("获取商户信息失败,mchntNo:<{}>", mchntOrderInfo.getMchntNo());
                throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
            }
            //获取交易配置信息
            TxnInfoService txnInfoService = new TxnInfoServiceImpl();
            TxnInfo txnInfo = txnInfoService.getTxnInfo(userOrderInfo.getInstId(), userOrderInfo.getMsgSrcId(), userOrderInfo.getTransChannelId(), userOrderInfo.getTxnNum(), userOrderInfo.getBizType());

            Optional<ChannelCallCfg> channelCallCfgOptional = txnInfo.getChannelCallCfgList().stream().filter(item -> ChannelEnum.ACCT.getChannelType().equals(item.getCallChannelId())).findFirst();
            if (!channelCallCfgOptional.isPresent()) {
                rglog.error("该交易码:{},映射关系表无虚拟账户记账数据！,sysSeqNum:<{}>,", mchntOrderInfo.getTxnNum(), sysSeqNum);
                throw new BizException(RespCodeEnum.CHANNEL_CONFIG_NOT_EXIST.getRespCode(), RespCodeEnum.CHANNEL_CONFIG_NOT_EXIST.getRespDesc());
            }
            //获取通道服务调用配置
            ChannelCallCfg channelCallCfg = channelCallCfgOptional.get();
            PayOrderInfo acctPayOrderInfo = initPayOrderInfo(mchntOrderInfo, channelCallCfg);
            /* 记账前登记支付订单表 */
            OrderService orderService = new OrderServiceImpl();
            if (!orderService.registerOrderInfo(null, null, acctPayOrderInfo)) {
                rglog.error("异步记账，登记虚拟账户记账支付订单失败！");
                return -1;
            }

            //调用多商户虚拟账户记账
            cc.rengu.igas.acct.facade.base.Header header = new cc.rengu.igas.acct.facade.base.Header();
            header.setInstId(userOrderInfo.getInstId());
            header.setTxnNum("P01AT002");
            header.setTraceNo(sysSeqNum + "0");
            header.setSrcSysId(AppParamConstant.SYS_ID);
            header.setChanlId(BspsAppParamConstant.BSP_SYS_ID);
            header.setTransTime(DateUtil.getCurrentTime());
            header.setTransDate(DateUtil.getCurrentDate());
            VirtAcctMultiMchntAdjustRequest virtAcctMultiMchntAdjustRequest = new VirtAcctMultiMchntAdjustRequest();
            virtAcctMultiMchntAdjustRequest.setHeader(header);
            virtAcctMultiMchntAdjustRequest.setAcctType("00");
            //借出贷入，默认贷-C ，借-D 入款
            virtAcctMultiMchntAdjustRequest.setDebitCreditFlag("C");

            List<MchtAdjustDetail> mchtAdjustDetailListFinal = new ArrayList<>();
            /*按商户分组去重，累计求和*/

            MchtAdjustDetail mchtAdjustDetail = new MchtAdjustDetail();
            //userType : 00-商户  01-会员 02-营销
            mchtAdjustDetail.setUserType("00");
            if (MchntTypeEnum.CHAIN_MCHNT_STORE.getMchntType().equals(mchntInfo.getMchntType()) && BspsAppParamConstant.FLAG_N.equals(mchntInfo.getIndependentDataFlag())) {
                //连锁商户门店非独立维护,填连锁商户号
                mchtAdjustDetail.setUserId(mchntInfo.getChainMchntNo());
            } else {
                mchtAdjustDetail.setUserId(mchntInfo.getMchntNo());
            }
            mchtAdjustDetail.setTransAmt(acctPayOrderInfo.getRealPayAmt());
            mchtAdjustDetailListFinal.add(mchtAdjustDetail);
            virtAcctMultiMchntAdjustRequest.setMchtAdjustDetailList(mchtAdjustDetailListFinal);
            DubboService dubboService = new DubboServiceImpl();
            int iReturnCode = dubboService.asynCallDubboService("virtAcctService", "virtAcctMultiMchntAdjust", virtAcctMultiMchntAdjustRequest, "AsynVirtAcctMultiMchntAdjustService");
            if (iReturnCode != 0) {
                rglog.error("异步虚拟账户记账服务注册失败！");
            }

            /*单商户记账,share不支持,弃用*/
            // VirtAcctSingleAdjustRequest virtAcctSingleAdjustRequest = new VirtAcctSingleAdjustRequest();
            // cc.rengu.igas.acct.facade.base.Header header = new cc.rengu.igas.acct.facade.base.Header();
            // header.setInstId(userOrderInfo.getInstId());
            // header.setTxnNum(channelCallCfg.getCallChannelTxn());
            // header.setTraceNo(sysSeqNum + channelCallCfg.getCallIndex());
            // header.setSrcSysId(AppParamConstant.SYS_ID);
            // header.setChanlId(BspsAppParamConstant.BSP_SYS_ID);
            // header.setTransTime(DateUtil.getCurrentTime());
            // header.setTransDate(DateUtil.getCurrentDate());
            // virtAcctSingleAdjustRequest.setHeader(header);
            // virtAcctSingleAdjustRequest.setAcctType("00");
            // //借出贷入，默认贷-C ，借-D 入款
            // virtAcctSingleAdjustRequest.setDebitCreditFlag("C");
            // //userType : 00-商户  01-会员 02-营销
            // virtAcctSingleAdjustRequest.setUserType("00");
            // virtAcctSingleAdjustRequest.setTransAmt(acctPayOrderInfo.getRealPayAmt());
            // if (MchntTypeEnum.CHAIN_MCHNT_STORE.getMchntType().equals(mchntBaseInfo.getMchntType()) && BspsAppParamConstant.FLAG_N.equals(mchntBaseInfo.getIndependentDataFlag())) {
            //     //连锁商户门店非独立维护,填连锁商户号
            //     virtAcctSingleAdjustRequest.setUserId(mchntBaseInfo.getChainMchntNo());
            // } else {
            //     virtAcctSingleAdjustRequest.setUserId(mchntOrderInfo.getMchntNo());
            // }
            //
            // DubboService dubboService = new DubboServiceImpl();
            // Result<VirtAcctSingleAdjustResponse> result = (Result<VirtAcctSingleAdjustResponse>) dubboService.callDubboService("virtAcctService","virtAcctSingleAdjust",virtAcctSingleAdjustRequest);
            // VirtAcctSingleAdjustResponse virtAcctSingleAdjustResponse = result.getResult();
            // if (result.isSuccess() && "00".equals(virtAcctSingleAdjustResponse.getTransStatus())) {
            //     mchntOrderInfo.setVirtualAcctBalance(virtAcctSingleAdjustResponse.getAfterBalance());
            //     mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime(BspsAppParamConstant.yyyy_MM_dd_HHmmssSSS));
            //
            //     acctPayOrderInfo.setSettleDate(virtAcctSingleAdjustResponse.getAcctDate());
            //     acctPayOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
            //     acctPayOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
            //     acctPayOrderInfo.setRespCode(virtAcctSingleAdjustResponse.getRespCode());
            //     acctPayOrderInfo.setRespDesc(virtAcctSingleAdjustResponse.getRespDesc());
            //     acctPayOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime(BspsAppParamConstant.yyyy_MM_dd_HHmmssSSS));
            //
            // } else if ("01".equals(virtAcctSingleAdjustResponse.getTransStatus())) {
            //     mchntOrderInfo.setVirtualAcctBalance(virtAcctSingleAdjustResponse.getAfterBalance());
            //     mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime(BspsAppParamConstant.yyyy_MM_dd_HHmmssSSS));
            //
            //     acctPayOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            //     acctPayOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
            //     acctPayOrderInfo.setSettleDate(virtAcctSingleAdjustResponse.getAcctDate());
            //     acctPayOrderInfo.setRespCode(virtAcctSingleAdjustResponse.getRespCode());
            //     acctPayOrderInfo.setRespDesc(virtAcctSingleAdjustResponse.getRespDesc());
            //     acctPayOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime(BspsAppParamConstant.yyyy_MM_dd_HHmmssSSS));
            // }
            //
            // if (!orderService.updateOrderInfo(null, Arrays.asList(mchntOrderInfo), acctPayOrderInfo)) {
            //     rglog.error("异步记账，更新虚拟账户支付订单表失败！");
            //     return -1;
            // }

        } catch (Exception e) {
            rglog.error(e.getMessage());
            rglog.error("异步进行虚拟账户记账失败，exception:{}", e);
        }

        return 0;
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }

    private PayOrderInfo initPayOrderInfo(MchntOrderInfo mchntOrderInfo, ChannelCallCfg channelCallCfg) throws Exception {
        PayOrderInfo payOrderInfo = new PayOrderInfo();
        payOrderInfo.setInstId(mchntOrderInfo.getInstId());
        payOrderInfo.setTxnDate(DateUtil.getCurrentDate());
        payOrderInfo.setTxnTime(DateUtil.getCurrentTime());
        payOrderInfo.setTxnNum(mchntOrderInfo.getTxnNum());
        payOrderInfo.setBizType(mchntOrderInfo.getBizType());
        payOrderInfo.setSysSeqNum(mchntOrderInfo.getSysSeqNum());
        payOrderInfo.setMchntOrderId(mchntOrderInfo.getMchntOrderId());
        payOrderInfo.setMchntNo(mchntOrderInfo.getMchntNo());
        payOrderInfo.setUserId(mchntOrderInfo.getUserId());
        payOrderInfo.setOrderCcy(mchntOrderInfo.getOrderCcy());
        payOrderInfo.setOrderAmt(mchntOrderInfo.getOrderAmt());
        //交易通道标识
        payOrderInfo.setMsgDstId(channelCallCfg.getCallChannelId());
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(mchntOrderInfo.getInstId(), mchntOrderInfo.getMchntNo());
        if (null == mchntInfo) {
            rglog.error("获取商户信息失败,mchntNo:<{}>", mchntOrderInfo.getMchntNo());
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        if (mchntInfo.getMchntSettleMode().endsWith("1")) {
            //收支两线的区别登记,手续费由支出户支出,虚拟记账记清算本金
            payOrderInfo.setRealPayAmt(mchntOrderInfo.getRealSettleAmt());
        } else {
            payOrderInfo.setRealPayAmt(mchntOrderInfo.getMchntSettleAmt());
        }

        String channelSeqNum = mchntOrderInfo.getSysSeqNum() + "0";
        payOrderInfo.setChannelSeqNum(channelSeqNum);
        payOrderInfo.setChannelReconKey(channelSeqNum);
        payOrderInfo.setDstCallIndex("0");
        payOrderInfo.setDstTxnNum(channelCallCfg.getCallChannelTxn());
        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        //虚拟账户与营销默认 “*”
        payOrderInfo.setPayType("*");
        payOrderInfo.setCreateTime(DateUtil.getCurrentDateTime(BspsAppParamConstant.yyyy_MM_dd_HHmmssSSS));

        return payOrderInfo;
    }

}
